import { defineStore } from 'pinia';
import { ref } from 'vue';
import { get_timeline } from '../tauriApi';

export interface TimelineItem {
  id: string;
  message: string;
  author?: string;
  timestamp: number; // Unix timestamp in ms
  source: string; // 'local-history', 'git', etc.
  iconClass?: string;
  resourceUri?: string; // file path this timeline item relates to
  command?: {
    action: string;
    args?: any;
  };
  contextValue?: string;
}

export const useTimelineStore = defineStore('timeline', () => {
  const currentUri = ref<string>('');
  const items = ref<TimelineItem[]>([]);
  const loading = ref(false);

  let refreshTimer: any = null;

  async function loadTimeline(uri: string, forceRefresh: boolean = false) {
    if (!uri || (!forceRefresh && currentUri.value === uri)) return;
    
    currentUri.value = uri;
    loading.value = true;
    items.value = [];

    try {
      const result = await get_timeline(uri);
      items.value = result.map((item: any) => {
        const src = String(item.source || '').toLowerCase().trim();
        const normalizedSource = src === 'git' ? 'git' : (src.includes('local') || src.includes('history') ? 'local-history' : src);
        return ({
          ...item,
          source: normalizedSource,
          resourceUri: uri,
          command: {
            action: 'diff',
            args: {
              resourceUri: uri,
              id: item.id,
              source: normalizedSource,
            }
          }
        });
      }).sort((a: TimelineItem, b: TimelineItem) => b.timestamp - a.timestamp);
    } catch (error) {
      console.error('Failed to load timeline:', error);
    } finally {
      loading.value = false;
    }
  }

  async function refreshTimeline() {
    if (!currentUri.value) return;
    if (refreshTimer) clearTimeout(refreshTimer);
    refreshTimer = setTimeout(() => {
      loadTimeline(currentUri.value, true);
    }, 200);
  }

  function clear() {
    currentUri.value = '';
    items.value = [];
  }

  return {
    currentUri,
    items,
    loading,
    loadTimeline,
    refreshTimeline,
    clear,
  };
});